<template>
    <div class="wrap">
        <el-dialog
                title="积分兑换"
                :visible.sync="exchangeShow"
                :show-close="false"
                :before-close="handleClose"
                @open="onOpen"
                ref="dialog"
                width="400px">
            <el-form class="form" :rules="rules" :model="exchangeForm" ref="ruleForm">
                <el-form-item label="商品" :label-width="formLabelWidth">
                    <el-input v-model="exchangeForm.name" disabled></el-input>
                    <img class="little-icon" src="../../assets/icons/cargo.png"/>
                </el-form-item>
                <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
                    <el-input v-model="exchangeForm.phone" placeholder="请输入手机号"/>
                    <img class="little-icon" src="../../assets/icons/ic_phone_iphone.png"/>
                </el-form-item>
                <el-form-item label="验证码" :label-width="formLabelWidth" prop="checkCode">
                    <el-input v-model="exchangeForm.checkCode" placeholder="请输入验证码"/>
                    <div @click.stop="bindSendCheckCode" class="bind_code_gain" :disabled="disabled">{{ btnText }}
                    </div>
                    <img class="little-icon" src="../../assets/icons/security.png"/>
                </el-form-item>
            </el-form>
            <div class="num">
                <div> 数量</div>
                <el-input-number v-model="exchangeForm.num" :min="1" :max="999"
                                 @blur="handleChange"></el-input-number>
            </div>
            <div slot="footer" class="dialog-footer">
                <div class="total-jiesuan">
                    <span style="padding-bottom: 0.2rem">所需积分:</span>
                    <div class="totalIntegral">{{total}}</div>
                </div>
                <el-button type="primary" @click="submit">兑 换</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {sendMessage} from '@/utils/apis/message'
    import {exchangeIt} from '@/utils/apis/integral'

    export default {
        name: "Exchange",
        data() {
            let checkPhone = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error("请输入手机号"));
                } else if (!/^1(3|4|5|6|7|8)\d{9}$/.test(value)) {
                    // 引入methods中封装的检查手机格式的方法
                    callback(new Error("请输入正确的手机号!"));
                } else {
                    callback();
                }
            };
            return {
                exchangeForm: {
                    name: '',
                    goodId: '',
                    phone: '',
                    checkCode: '',
                    num: 1
                },
                rules: {
                    phone: [{validator: checkPhone, trigger: 'blur'}],
                    checkCode: [{
                        validator: (rule, value, callback) => {
                            if (value.length !== 6 || value.search(/[A-Za-z]+/) >= 0) {
                                callback(new Error('验证码格式不正确'))
                            } else {
                                callback();
                            }
                        }, trigger: 'blur'
                    }]
                },
                formLabelWidth: '80px',
                //能否发送验证码
                btnText: "发送验证码",
                disabled: true
            }
        },
        props: ['exchangeShow', 'userPhone', 'good'],
        computed: {
            total() {
                return this.good.exchange * this.exchangeForm.num
            }
        },
        methods: {
            handleClose() {
                this.$refs['ruleForm'].clearValidate()
                this.$notify.info('取消兑换')
                this.cancel()
            },
            cancel() {
                this.$emit('cancel')
            },
            //打开窗口的回调
            onOpen() {
                if (this.userPhone !== '') {
                    this.exchangeForm.phone = this.userPhone
                }
                this.phone = this.userPhone
                this.exchangeForm.goodId = this.good.id
                this.exchangeForm.name = this.good.name
            },
            //防止数量为''
            handleChange() {
                if (this.exchangeForm.num === undefined) {
                    this.exchangeForm.num = 1
                }
            },
            //发送验证码
            async bindSendCheckCode() {
                //通过手机号校验
                if (/^1(3|4|5|6|7|8)\d{9}$/.test(this.exchangeForm.phone)) {
                    const loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        // spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    await sendMessage(this.exchangeForm.phone).then(res => {
                        this.$message.success('验证码已发送')
                        this.doLoop(60);
                        loading.close()
                    })
                } else {
                    this.$message.warning('手机号格式不正确')
                }
            },
            // 手机验证码的倒计时
            doLoop(seconds) {
                seconds = seconds ? seconds : 60;
                this.btnText = seconds + "s后获取";
                // this.code = code
                let countdown = setInterval(() => {
                    if (seconds > 0) {
                        this.btnText = seconds + "s后获取";
                        --seconds;
                    } else {
                        this.btnText = "获取验证码";
                        this.disabled = false;
                        clearInterval(countdown);
                    }
                }, 1000);
            },
            //确认兑换
            submit() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        const data = {
                            id: this.good.id,
                            num: this.exchangeForm.num,
                            phone: this.exchangeForm.phone
                        }
                        exchangeIt(data, this.exchangeForm.checkCode).then(res => {
                            this.$message.success('兑换成功,请至福利领取处领取您的奖品~')
                            this.cancel()
                        })
                    }
                })
            },
        }
    }
</script>
<style scoped>

    .form /deep/ .el-input__inner {
        height: 44px;
        background: #f7f7f7;
        border-radius: 4px;
        border: 1px solid #e4e4e4;
        outline: none;
        padding: 0 100px 0 30px !important;
    }


    .little-icon {
        width: 20px;
        height: 20px;
        position: absolute;
        top: 12px;
        left: 8px;
    }

    .bind_code_gain {
        position: absolute;
        top: calc(50% - 9px);
        right: 10px;
        font-size: 14px;
        font-family: MicrosoftYaHei;
        color: #3a75e8;
        line-height: 18px;
        cursor: pointer;
        padding-left: 10px;
        border-left: 1px solid #d8d8d8;
    }

    .num {
        display: flex;
        justify-content: space-around;
        align-items: center;
    }

    .dialog-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .total-jiesuan {
        display: flex;
        justify-content: center;
        align-items: end;
        color: #8e9aaf;
        font-size: 10px;
        padding-left: 1rem;
    }

    .totalIntegral {
        color: rgba(234, 108, 46, 0.8);
        font-size: 24px;
    }
</style>